package com.mflex.WHSmartWhouseAd.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.mflex.WHSmartWhouseAd.R;
import com.mflex.WHSmartWhouseAd.adapter.InventoryListBoxAdapter;
import com.mflex.WHSmartWhouseAd.adapter.QMSInventoryBoxAdapter;
import com.mflex.WHSmartWhouseAd.model.CommitSamplinginspectionModel;
import com.mflex.WHSmartWhouseAd.model.CommonRequest;
import com.mflex.WHSmartWhouseAd.model.QMSInventoryDetailsPdaInfo;
import com.mflex.WHSmartWhouseAd.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
//
//import butterknife.BindView;
//import butterknife.ButterKnife;


public class QMSSamplingInspectionActivity extends BaseActivity implements AdapterView.OnItemClickListener  {
    // 料号

    EditText stvPartNo;
    // 任务单号

    EditText stvTask;
    // 需求数量

    EditText stvQuantityRequired;
    // 扫描数量

    EditText stvActualScanNumber;
    // 包号/盘号

    EditText stvPackageNumber;
    // 列表

    ListView lvList;
    // 清空

    Button buttonClear;
    // 提交

    Button buttonSubmit;

    // loading
    MiniLoadingDialog miniLoadingDialog;
    List<QMSInventoryDetailsPdaInfo>QMSInventoryModelList=new ArrayList<>();
    CommitSamplinginspectionModel model = new CommitSamplinginspectionModel();
    private String userName;
    private String VehicleNo;
    private String MaterialType;
    private double ActualScanNumber=0;//扫描数量
    private String ActualQuantityRequired;//需求数量
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_qms_sampling_inspection);
//        ButterKnife.bind(this);

        stvPartNo=findViewById(R.id.stv_PartNo);
        stvTask=findViewById(R.id.stv_Task);
        stvQuantityRequired=findViewById(R.id.stv_QuantityRequired);
        stvActualScanNumber=findViewById(R.id.stv_ActualScanNumber);
        stvPackageNumber=findViewById(R.id.stv_PackageNumber);
        lvList=findViewById(R.id.lvList);
        buttonClear=findViewById(R.id.button_clear);
        buttonSubmit=findViewById(R.id.button_submit);
        // 弹窗提示
        miniLoadingDialog =WidgetUtils.getMiniLoadingDialog(this,"加载...");
        // 传递数据
        Intent intent = getIntent();
        userName = intent.getStringExtra("User");
        VehicleNo = intent.getStringExtra("VehicleNumber");
        stvTask.setText(intent.getStringExtra("TaskNo").replace("\"", ""));
        MaterialType = intent.getStringExtra("MaterialType").replace("\"", "");
        stvPartNo.setText(intent.getStringExtra("MPart").replace("\"", ""));
        ActualQuantityRequired = intent.getStringExtra("Qty").replace("\"", "");
        Log.d("VehicleNo",VehicleNo);
        // 视图按键监听器
        stvPackageNumber.setOnKeyListener(this);
        buttonSubmit.setOnClickListener(this);
        buttonClear.setOnClickListener(this);
        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));//扫描数量
        stvQuantityRequired.setText(String.valueOf(ActualQuantityRequired));//需求数量
        stvPackageNumber.requestFocus();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                QMSInventoryModelList.clear();
                QMSInventoryBoxAdapter QMSInventoryBoxAdapter = new QMSInventoryBoxAdapter(QMSSamplingInspectionActivity.this,QMSInventoryModelList);
                lvList.setAdapter(QMSInventoryBoxAdapter);
                stvPackageNumber.setText("");
                ActualScanNumber = 0;
                stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                break;
            case R.id.button_submit:
                saveButtonMd(view);
                break;
            default:
                break;
        }

    }
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_PackageNumber: // 包号/盘号
                    chekPackageNumber();
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    //    箱号回车事件触发接口
    private void chekPackageNumber() {
        if(StringUtils.isEmpty(stvPackageNumber.getText().toString())) {
            return;
        }


        //      测试
//        QMSInventoryDetailsPdaInfo people = new QMSInventoryDetailsPdaInfo();
//        double adm =   Math.random();
//        people.setVehNo("123"+adm);
//        people.setReelId("盘号");
//        people.setShrinkType("涨缩");
//        people.setERPLot("lot");
//        people.setQty(String.valueOf(10));
//        ActualScanNumber +=Double.parseDouble(people.getQty());
//        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
//        QMSInventoryModelList.add(people);
//        QMSInventoryBoxAdapter QMSInventoryBoxAdapter = new QMSInventoryBoxAdapter(QMSSamplingInspectionActivity.this,QMSInventoryModelList);
//
//        lvList.setAdapter(QMSInventoryBoxAdapter);

//      结束
        // 累加数量不能大于需求数
        int num2=(int)Math.round(Double.parseDouble(ActualQuantityRequired));
        if(ActualScanNumber >= num2) {
            MediaPlayer mp = MediaPlayer.create(QMSSamplingInspectionActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(QMSSamplingInspectionActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("超出需求数量！")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        boolean ischeck = true;
        // 重复扫描卡控
        if(!QMSInventoryModelList.isEmpty()) {
            for(QMSInventoryDetailsPdaInfo item: QMSInventoryModelList) {
                if(Objects.equals(item.getReelId(), stvPackageNumber.getText().toString())) {
                    ischeck = false;
                    break;
                }
            }
        }
        if(!ischeck) {
            MediaPlayer mp = MediaPlayer.create(QMSSamplingInspectionActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(QMSSamplingInspectionActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("包号"+stvPackageNumber.getText().toString()+"在列表中已存在")
                    .positiveText(R.string.lab_submit)
                    .show();
            stvPackageNumber.setText("");
            stvPackageNumber.requestFocus();
            return;

        }
        miniLoadingDialog.show();
        XHttp.get("api/WHSmartWhousePDA/GetInventoryDetails2")
                .params("VehicleNumber",VehicleNo)
                .params("ReelId",stvPackageNumber.getText().toString())
                .params("MaterialType",MaterialType)
//                .params("TaskNo",stvTask.getText().toString().trim())
                .syncRequest(false)
                .onMainThread(true)
                .execute(new SimpleCallBack<List<QMSInventoryDetailsPdaInfo>>() {
                    @Override
                    public  void  onSuccess(List<QMSInventoryDetailsPdaInfo> response) {
                        miniLoadingDialog.dismiss();


                        // 循环添加箱号数据
                        for(QMSInventoryDetailsPdaInfo item : response) {
                            // 累加数量
                            ActualScanNumber +=Double.parseDouble(item.getQty());
                            QMSInventoryModelList.add(item);
                        }
                        QMSInventoryBoxAdapter QMSInventoryBoxAdapter = new QMSInventoryBoxAdapter(QMSSamplingInspectionActivity.this,QMSInventoryModelList);

                        lvList.setAdapter(QMSInventoryBoxAdapter);

                        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                        stvPackageNumber.setText("");
                        stvPackageNumber.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp = MediaPlayer.create(QMSSamplingInspectionActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(QMSSamplingInspectionActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }
                });

    }
    private void saveButtonMd(View v) {
        if(QMSInventoryModelList.isEmpty()) {
            MediaPlayer mp = MediaPlayer.create(QMSSamplingInspectionActivity.this,R.raw.error_voice);mp.start();
            new MaterialDialog.Builder(QMSSamplingInspectionActivity.this)
                    .iconRes(R.drawable.icon_warning)
                    .title(R.string.tip_warning)
                    .content("盘号/包号未输入")
                    .positiveText(R.string.lab_submit)
                    .show();
            return;
        }
        List<CommitSamplinginspectionModel> dataList = new ArrayList<>();
        for( QMSInventoryDetailsPdaInfo item : QMSInventoryModelList) {
            CommitSamplinginspectionModel entity= new CommitSamplinginspectionModel();
            entity.setTaskNo(stvTask.getText().toString());
            entity.setVehicleNumber(item.getVehNo());
            entity.setReelId(item.getReelId());
            entity.setERPlot(item.getERPLot());
            entity.setMPart(item.getMPart());
            entity.setMType(item.getMType());
            entity.setUser(userName);
            dataList.add(entity);
        }

        CommonRequest request =new CommonRequest();
        request.setJson(JsonUtil.toJson(dataList));
        String json = JsonUtil.toJson(dataList);
        miniLoadingDialog.show();
        XHttp.post("api/WHSmartWhousePDA/CommitQMSInspectionData")
                .upJson(JsonUtil.toJson(request))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onSuccess(String response) {
                        miniLoadingDialog.dismiss();
                        XToastUtils.success("提交成功",3000);
                        QMSInventoryModelList.clear();
                        QMSInventoryBoxAdapter QMSInventoryBoxAdapter = new QMSInventoryBoxAdapter(QMSSamplingInspectionActivity.this,QMSInventoryModelList);
                        lvList.setAdapter(QMSInventoryBoxAdapter);
                        ActualScanNumber = 0;
                        stvActualScanNumber.setText(String.valueOf(ActualScanNumber));
                        stvPackageNumber.setText("");
                        stvPackageNumber.requestFocus();
                    }
                    @Override
                    public void onError(ApiException e) {
                        miniLoadingDialog.dismiss();
                        MediaPlayer mp =MediaPlayer.create(QMSSamplingInspectionActivity.this,R.raw.error_voice);mp.start();
                        new MaterialDialog.Builder(QMSSamplingInspectionActivity.this)
                                .iconRes(R.drawable.icon_warning)
                                .title(R.string.tip_warning)
                                .content(e.getMessage())
                                .positiveText(R.string.lab_submit)
                                .show();
                    }

                });
    }




    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}